capture prog drop WAD_ROSLA_RF_gen_lin
program WAD_ROSLA_RF_gen_lin, rclass

version 13
syntax varlist, Generate(name) [pctl(real 1) pctu(real 99) ctff(real 0) bw(real 120)]

	confirm new variable `generate'
	tempvar tempy z eval drd eval_iter drd_iter f ksstat absksstat after xafter x2 x2after thequant clustadjust
	local y : word 1 of `varlist'
	local x : word 2 of `varlist'
	local covstemp : list varlist - y
	cap local covs : list covstemp - x
	
qui gen `tempy'=0
qui gen `after'=(`x'>=`ctff')
* qui gen `x2'=`x'^2
qui gen `xafter'=`x'*`after'
* qui gen `x2after'=`x2'*`after'

return scalar bw=`bw'

qui sum `y' if abs(`x')<`bw'
scalar nobs=r(N)

qui gen `z'=`ctff' in 1
qui gen `eval'=.
qui gen `drd'=.
forvalues i = `pctl'(1)`pctu' {
	local qt=`i'/100
	qui centile `y' if abs(`x')<`bw', centile(`i')
	local cen=r(c_1)
	qui replace `tempy'=(`y'<=`cen')
*	qui reg `tempy' `after' `x' `x2' `xafter' `x2after' `covs' if abs(`x')<`bw' [aw=`bw'-abs(`x')]
	qui reg `tempy' `after' `x' `xafter' `covs' if abs(`x')<`bw' [aw=`bw'-abs(`x')]
	qui replace `drd'=_b[`after']  in `i'
*	qui reg `tempy' `x' `x2' if abs(`x')<`bw' & `x'<0 & edu16==0 [aw=`bw'-abs(`x')]
	qui reg `tempy' `x' if abs(`x')<`bw' & `x'<0 & edu16==0 [aw=`bw'-abs(`x')]
	qui replace `eval'=_b[_cons] in `i'
}
qui gen theQ=_n/100 in 1/99
qui gen `generate'=`drd'

qui gen `thequant'=_n in 1/100

qui replace `generate'=`generate'^2/(theQ*(1-theQ))
qui gen `generate'Q=`eval'
qui sum `generate'
local thestat=r(mean)
qui drop theQ

disp `thestat'

end
